package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.mapper.ItemClient;
import com.hmall.mapper.UserClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserClient userClient;
    @Override
    public Long commitOrderById(RequestParams params) {
        //使用雪花算法生成订单id---MP提供的工具类
        long orderId = IdWorker.getId();
        //3. 通过远程调用id查询商品的接口，查询商品相关信息
        Long itemId = params.getItemId();
        Item item = itemClient.getById(itemId);
        //4.基于商品价格、购买数量计算商品总价：totalFee
        Long price = item.getPrice();
        Integer num = params.getNum();
        //计算总价
        Long totalFee = price * num;
        Order order = new Order();
        order.setTotalFee(totalFee);
        //5. 初识status为未支付
        order.setStatus(1);
        //6. 写入数据库------>新增
        orderMapper.insert(order);
        //7. 将商品信息、orderId信息
        // 封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemId(itemId);
        orderDetail.setOrderId(orderId);
        orderDetailMapper.insert(orderDetail);
        //8. 将user-service的根据id查询地址接口封装为FeignClient
        //9. 根据addressId查询user-service服务，获取地址信息
        Long addressId = params.getAddressId();
        Address address = userClient.findAddressByAddressId(addressId);
        //10 将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        /*String province = address.getProvince();
        String city = address.getCity();
        String town = address.getTown();
        String street = address.getStreet();
        orderLogistics.setProvince(province);
        orderLogistics.setCity(city);
        orderLogistics.setTown(town);
        orderLogistics.setStreet(street);*/
        BeanUtils.copyProperties(address,orderLogistics);

        return null;
    }
}
